package com.eddie.juc.interrupt;

import lombok.SneakyThrows;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author Eddie
 * @date 2022/08/20 10:19
 **/
public class InterruptDemo {

    static volatile boolean isStop = false;
    static AtomicBoolean atomicBoolean = new AtomicBoolean(false);

    @SneakyThrows
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println(Thread.currentThread().getName() + "\tisInterrupted被修改为true，程序终止");
                    break;
                }
                System.out.println("--------hello isInterrupted");
            }
        }, "t1");
        t1.start();
        TimeUnit.MILLISECONDS.sleep(20);
        new Thread(() -> {
            //发起一个协商，而不会立即中断线程
           t1.interrupt();
        }, "t2").start();
    }

    private static void m2AtomicBoolean() throws InterruptedException {
        new Thread(() -> {
            while (true) {
                if(atomicBoolean.get()) {
                    System.out.println(Thread.currentThread().getName()+"\tisStop被修改为true，程序终止");
                    break;
                }
                System.out.println("--------hello atomicBoolean");
            }
        }, "t1").start();
        TimeUnit.MILLISECONDS.sleep(20);
        new Thread(() -> {
            atomicBoolean.set(true);
        }, "t2").start();
    }

    private static void m1Volatile() throws InterruptedException {
        new Thread(() -> {
             while (true) {
                 if(isStop) {
                     System.out.println(Thread.currentThread().getName()+"\tisStop被修改为true，程序终止");
                     break;
                 }
                 System.out.println("--------hello volatile");
             }
        }, "t1").start();
        TimeUnit.MILLISECONDS.sleep(20);
        new Thread(() -> {
            isStop=true;
        }, "t1").start();
    }
}
